package com.right.health.app.ui.main.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.magic.basic.utils.ToastUtil;
import com.magic.basic.widget.CircleImageView;
import com.magics.http.listener.OnHttpListener;
import com.magics.http.model.Request;
import com.magics.http.model.Response;
import com.right.health.app.R;
import com.right.health.app.app.App;
import com.right.health.app.base.BasePresenterFragment;
import com.right.health.app.bean.AppUserResponse;
import com.right.health.app.constants.AppConfig;
import com.right.health.app.dialog.ProfileCertificationDialog;
import com.right.health.app.net.UserApi;
import com.right.health.app.ui.common.AboutActivity;
import com.right.health.app.ui.common.ArticleDetailActivity;
import com.right.health.app.ui.me.DataAuthorizationActivity;
import com.right.health.app.ui.me.DrugRemindActivity;
import com.right.health.app.ui.me.FamilyActivity;
import com.right.health.app.ui.me.FeedbackActivity;
import com.right.health.app.ui.me.MeQrcodeActivity;
import com.right.health.app.ui.me.MeReserveActivity;
import com.right.health.app.ui.me.MeVisitCardActivity;
import com.right.health.app.ui.me.MyServicePackActivity;
import com.right.health.app.ui.me.ReviewReminderActivity;
import com.right.health.app.ui.me.SettingsActivity;
import com.right.health.app.ui.me.ShippingAddressActivity;
import com.right.health.app.ui.me.SocialSecurityInfoActivity;
import com.right.health.app.ui.user.CertificationByArtificialActivity;
import com.right.health.app.ui.user.CertificationByCardActivity;
import com.right.health.app.ui.user.CertificationByHospitalActivity;
import com.right.health.app.ui.user.LoginActivity;
import com.right.health.app.ui.user.ProfileActivity;
import com.right.health.app.utils.GlideUtil;

import static com.right.health.app.constants.BroadCastCode.REFRESH_USER;

/*
 * Created by hopeliao on 2019-09-23
 *
 */
public class MeFragment extends BasePresenterFragment implements View.OnClickListener, OnHttpListener {

    private static final int HTTP_CODE_GET_USER_INFO = 1;

    private ProfileCertificationDialog mCertificationDialog;

    private CircleImageView mAvatarImage;

    private TextView mUserNameTv, mCertificationTipsTv,mUnAuthrnticateLable;

    private UserApi mUserApi;

    @Override
    public View onCreateView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle bundle, String s) {
        return layoutInflater.inflate(R.layout.me, viewGroup, false);
    }

    @Override
    public void findView() {
        mAvatarImage = (CircleImageView) findViewById(R.id.iv_avatar);
        mUserNameTv = (TextView) findViewById(R.id.tv_name);
        mCertificationTipsTv = (TextView) findViewById(R.id.tv_certification_tips);
        mUnAuthrnticateLable = (TextView) findViewById(R.id.tv_unauthenticate_label);

        findViewById(R.id.iv_avatar).setOnClickListener(this);
        findViewById(R.id.me_item_8).setOnClickListener(this);
        findViewById(R.id.iv_qrcode).setOnClickListener(this);
        findViewById(R.id.tv_card_number).setOnClickListener(this);
        findViewById(R.id.me_item_9).setOnClickListener(this);
        findViewById(R.id.tv_me_reserve_item).setOnClickListener(this);
        findViewById(R.id.me_item_3).setOnClickListener(this);
        findViewById(R.id.me_item_10).setOnClickListener(this);
        findViewById(R.id.me_item_5).setOnClickListener(this);
        findViewById(R.id.tv_family_members).setOnClickListener(this);
        findViewById(R.id.me_item_4).setOnClickListener(this);
        findViewById(R.id.tv_social_security_card).setOnClickListener(this);
        findViewById(R.id.me_item_6).setOnClickListener(this);
        findViewById(R.id.me_item_7).setOnClickListener(this);
        findViewById(R.id.me_item_1).setOnClickListener(this);
        findViewById(R.id.me_item_2).setOnClickListener(this);
        findViewById(R.id.me_item_agreement).setOnClickListener(this);
        findViewById(R.id.me_item_address).setOnClickListener(this);
        findViewById(R.id.me_item_service).setOnClickListener(this);

    }

    @Override
    public void initialize() {
        mUserApi = new UserApi();
        mUserApi.setListener(this);

        refreshUI(App.getInstance().getUser());
        mUserApi.addRequestCode(HTTP_CODE_GET_USER_INFO);
        mUserApi.getUserInfo();
    }

    private void refreshUI(AppUserResponse.AppUserInfo userInfo) {
        Glide.with(App.getInstance()).load(AppConfig.PHOTO_URL + userInfo.imageurl).
                apply(GlideUtil.getDefaultPlaceholder(R.mipmap.ic_default_avatar)).into(mAvatarImage);

        mUserNameTv.setText(userInfo.personname);
        Drawable drawable;
        if (userInfo.isVertificationSucc()) {
           drawable = getResources().getDrawable(R.mipmap.ic_me_card);
        }else {
        drawable = getResources().getDrawable(R.mipmap.ic_me_dont_card);
        }
        mUserNameTv.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null);
        mUnAuthrnticateLable.setVisibility(userInfo.isVertificationSucc()?View.GONE:View.VISIBLE);
        mCertificationTipsTv.setText(userInfo.isVertificationSucc() ? "身份认证成功，可以查看您的医疗病例信息" : "暂未认证");
    }

    @Override
    public void onReceiveBroadcast(int intent, Bundle bundle) {
        super.onReceiveBroadcast(intent, bundle);
        if (intent == REFRESH_USER) {
            refreshUI(App.getInstance().getUser());
        }
    }

    @Override
    public void onClick(View v) {
        if (!isAdded()) {
            return;
        }
        switch (v.getId()) {
            case R.id.me_item_1: //认证
                if (TextUtils.equals(App.getInstance().getUser().verifystatus, "1")) {
                    ToastUtil.show(getActivity(), R.string.me_already_authenticated);
                } else {
                    if (mCertificationDialog == null) {
                        mCertificationDialog = new ProfileCertificationDialog(getActivity());
                        mCertificationDialog.setClickListener(this);
                    }
                    mCertificationDialog.show();
                }
                break;
            case R.id.tv_choose_type1: //医院预留信息认证
                startIntent(CertificationByHospitalActivity.class);
                dismiss();
                break;
            case R.id.tv_choose_type2: //身份证自动认证
                startIntent(CertificationByCardActivity.class);
                dismiss();
                break;
            case R.id.tv_choose_type3: //人工审核认证
                startIntent(CertificationByArtificialActivity.class);
                dismiss();
                break;
            case R.id.iv_avatar: //个人信息
                if (App.getInstance().isLogined()) {
                    startIntent(ProfileActivity.class);
                } else {
                    startIntent(LoginActivity.class);
                }
                break;
            case R.id.me_item_8: // 意见反馈
                startIntent(FeedbackActivity.class);
                break;
            case R.id.iv_qrcode: //二维码
                startIntent(MeQrcodeActivity.class);
                break;
            case R.id.tv_card_number: //就诊卡号
                startIntent(MeVisitCardActivity.class);
                break;
            case R.id.me_item_9: //关于我们
                startIntent(AboutActivity.class);
                break;
            case R.id.tv_me_reserve_item: //我的预约
                startIntent(MeReserveActivity.class);
                break;
            case R.id.me_item_3: //数据授权
                startIntent(DataAuthorizationActivity.class);
                break;
            case R.id.me_item_10: //设置
                startIntent(SettingsActivity.class);
                break;
            case R.id.me_item_5: //复诊提醒
                startIntent(ReviewReminderActivity.class);
                break;
            case R.id.tv_family_members: //家庭成员管理
                startIntent(FamilyActivity.class);
                break;
            case R.id.me_item_4: //用药提醒
                startIntent(DrugRemindActivity.class);
                break;
            case R.id.tv_social_security_card: //社保卡
                startIntent(SocialSecurityInfoActivity.class);
                break;
            case R.id.me_item_2: //我的设备
            case R.id.me_item_6:  //购买记录
            case R.id.me_item_7: //在线处方记录
                ToastUtil.show(App.getInstance(), R.string.not_yet_opened);
                break;
            case R.id.me_item_agreement:
                showAgreementDialog();
                break;
            case R.id.me_item_address:
                startIntent(ShippingAddressActivity.class);
                break;
            case R.id.me_item_service:
                startIntent(MyServicePackActivity.class);
                break;
        }
    }

    private String agreementPath = "";
    private String agreementName = "";
    private void showAgreementDialog() {
        agreementPath = "/pandWx/agreement/h5_provisions_declare.html";
        agreementName = "服务协议";
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("选择");
        builder.setSingleChoiceItems(new String[]{"服务协议", "隐私协议"}, 0, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (which==0){
                    agreementName = "服务协议";
                    agreementPath = "/pandWx/agreement/h5_provisions_declare.html";
                }else if (which==1){
                    agreementName = "隐私协议";
                    agreementPath = "/pandWx/agreement/h5_user_privacy.html";
                }
            }
        });
        builder.setPositiveButton("确定", (dialog, which) -> {
            ArticleDetailActivity.makeActivity(getActivity(), agreementName, AppConfig.HTTP_ADDRESS + agreementPath);
            dialog.dismiss();
        });
        builder.create().show();
    }


    private void dismiss() {
        if (mCertificationDialog != null && mCertificationDialog.isShowing()) {
            mCertificationDialog.dismiss();
        }
    }

    @Override
    public void onResponse(Request request, Response response) {
        if (!isAdded()) {
            return;
        }
        if (response.isResponseFail()) {
            ToastUtil.show(getActivity(), response.error);
        } else {
            if (response.targetData instanceof AppUserResponse) {
                AppUserResponse appUserResponse = response.cast(AppUserResponse.class);
                App.getInstance().refreshUser(appUserResponse.user);

                refreshUI(appUserResponse.user);
            }
        }
    }
}
